package com.marisfrolg.storage;

import java.lang.ref.WeakReference;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.DbException;
import com.marisfrolg.base.BaseApplication;
import com.marisfrolg.entity.json.User;
import com.marisfrolg.util.ReadCodeController;
import com.slidingmenu.lib.SlidingMenu;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ItemActivity extends Activity {
	public SlidingMenu menu;
	protected DbUtils db;
	protected Handler sHandler = new ScanHandler(this);
	protected MediaPlayer mediaPlayer = null;
	protected ProgressDialog progressDialog;
	protected User loginUser;
	private ReadCodeController rcc;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//保持屏幕常亮
		db=DbUtils.create(this,Environment.getExternalStorageDirectory().getPath() + "/storage/","storage.db");
		rcc=((BaseApplication)getApplication()).getReadCodeController();
		rcc.setHandler(sHandler);
		rcc.Open();
		menu = new SlidingMenu(this);
		// 设置滑动方向
		menu.setMode(SlidingMenu.LEFT);
		// 设置监听开始滑动的触碰范围
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		// 设置边缘阴影的宽度，通过dimens资源文件中的ID设置
		menu.setShadowWidthRes(R.dimen.shadow_width);
		// 设置边缘阴影的颜色/图片，通过资源文件ID设置
		menu.setShadowDrawable(R.drawable.shadow);
		// 设置menu全部打开后，主界面剩余部分与屏幕边界的距离，通过dimens资源文件ID设置
		menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		// 设置是否淡入淡出
		menu.setFadeEnabled(true);
		// 设置淡入淡出的值，只在setFadeEnabled设置为true时有效
		menu.setFadeDegree(0.35f);
		// 将menu绑定到Activity，同时设置绑定类型
		menu.attachToActivity(this, SlidingMenu.SLIDING_WINDOW);
		// 设置menu的layout
		menu.setMenu(R.layout.slide_menu);
		// 设置menu的背景
		menu.setBackgroundColor(getResources().getColor(
				android.R.color.background_light));
		try {
			TextView usernametitle = (TextView) menu
					.findViewById(R.id.usernametitle);
			loginUser=db.findFirst(User.class);
//			usernametitle.setText(loginUser.getUsername()+"\n"+loginUser.getWorklgnum());
			if(loginUser==null){
				loginUser=new User();
				loginUser.setId(-1);
				TelephonyManager TelephonyMgr = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
		        String szImei = TelephonyMgr.getDeviceId();
				loginUser.setImei(szImei);
				loginUser.setLoginname("匿名帐号" );
				loginUser.setUsername("匿名帐号");
				loginUser.setPassword("匿名帐号");
				loginUser.setWorklgnum("DSZ1");
			}
			usernametitle.setText(loginUser.getLoginname()+"\n"+loginUser.getWorklgnum());
			usernametitle.setTextColor(Color.BLACK);
		} catch (DbException e) {
			e.printStackTrace();
		}
		Button getDefferenceButton=(Button)this.findViewById(R.id.getdefference);
		getDefferenceButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent in=new Intent();
				in.setClass(ItemActivity.this, CheckedActivity.class);
				if(menu.isShown()){
					menu.toggle();
				}
				startActivity(in);
			}
		});
		Button setting=(Button)this.findViewById(R.id.setting);
		setting.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent in=new Intent();
				in.setClass(ItemActivity.this, SettingActivity.class);
				if(menu.isShown()){
					menu.toggle();
				}
				startActivity(in);
			}
		});
		Button quit=(Button)this.findViewById(R.id.quit);
		quit.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				android.os.Process.killProcess(android.os.Process.myPid());
			}
		});
		Button getProductStock=(Button)this.findViewById(R.id.getproductstock);
		getProductStock.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent in=new Intent();
				in.setClass(ItemActivity.this, ProductStockActivity.class);
				if(menu.isShown()){
					menu.toggle();
				}
				startActivity(in);
			}
		});
	}

	

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			menu.toggle();
		}
		if (keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10
				|| keyCode == KeyEvent.KEYCODE_F11) {
			rcc.scan_start();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10
				|| keyCode == KeyEvent.KEYCODE_F11) {
			rcc.scan_stop();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

	private static class ScanHandler extends Handler {
		WeakReference<ItemActivity> wactivity;

		ScanHandler(ItemActivity activity) {
			wactivity = new WeakReference<ItemActivity>(activity);
		}

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ReadCodeController.CODEREAD: {
				ItemActivity activity = wactivity.get();
				String old = msg.obj + "";
				View v=activity.getCurrentFocus();
				if (v instanceof EditText){
					EditText et=(EditText)v;
					et.setText(old);
				}
				activity.play_sound();
				break;
			}
			default:
				break;
			}
		}
	};
	public void play_sound(boolean success) {
		try {
			if(success){
				mediaPlayer = MediaPlayer.create(this, R.raw.success);
			}else{
				mediaPlayer = MediaPlayer.create(this, R.raw.error);
			}
			mediaPlayer.stop();
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void play_sound() {
		try {
			if (mediaPlayer == null)
				mediaPlayer = MediaPlayer.create(this, R.raw.beep);
			mediaPlayer.stop();
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
//
//	protected void onDestroy() {
//		rcc.Close();
//		rcc.setHandler(null);
//		super.onDestroy();
//	}
	@Override
	protected void onResume() {
		super.onResume();
		rcc.setHandler(sHandler);
	}
	@Override
	protected void onStart() {
		super.onStart();
		rcc.setHandler(sHandler);
	}

}
